package com.vxdata.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.vxdata.common.core.domain.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;

import java.time.LocalDateTime;

/**
 * @ClassName MybatisMetaObjectHandler
 * @Description mybatis自动填充插件
 * @Author cutepig
 * @Date 2021/7/9 9:52
 * @Version 1.0
 */
@Slf4j
public class MybatisMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        setFieldValByName("createDate", LocalDateTime.now(), metaObject);
        setFieldValByName("createBy", getCurrentUser(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateDate", LocalDateTime.now(), metaObject);
        setFieldValByName("updateBy", getCurrentUser(), metaObject);
    }

    private String getCurrentUser() {
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            return null;
        } else {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (!principal.equals("anonymousUser")) {
                LoginUser user = (LoginUser) principal;
                return user.getUsername();
            }
            return null;
        }
    }
}
